/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tuoc;

import java.sql.ResultSet;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author apple
 */
public class form_view extends javax.swing.JPanel {

    /**
     * Creates new form form_view
     */
    public int table_id;
    double totalMoney;
    Tuoc tuocController;
    
    public form_view() {
        tuocController = new Tuoc();
        initComponents();
    }
    
    public void set_search_table_data(Vector data)
    {
        DefaultTableModel model = (DefaultTableModel)tblSearchResult.getModel();
        model = this.removeAllRows(model);
        Iterator dataIter = data.iterator();
        while(dataIter.hasNext())
        {
            products_model currenObj = (products_model)dataIter.next();
            Vector row = new Vector();
            row.add(currenObj.id);
            row.add(currenObj.name);
            row.add(currenObj.unit);
            row.add(tuocController.priceWithoutDecimal(currenObj.price));
            model.addRow(row);
        }    
        tblSearchResult.setModel(model);
    }
    
    public void setTableId(int id)
    {
        table_id = id;
    }
    
    
    private DefaultTableModel removeAllRows(DefaultTableModel model)
    {
        while(model.getRowCount() > 0)
        {
            model.removeRow(0);
        }
        return model;
    }
    
    public DefaultTableModel get_search_model()
    {
        DefaultTableModel model = (DefaultTableModel)tblSearchResult.getModel();
        return model;
    }
    
    public void set_search_table_by_search(String key)
    {
        Vector data = new products_model().get_elements_by_keyword(key);
        this.set_search_table_data(data);
    }
    
    public void reloadTableOrder()
    {
        
        DefaultTableModel tblOrderModel = (DefaultTableModel)tblOrder.getModel();
        tblOrderModel = this.removeAllRows(tblOrderModel);
        Vector data = tuocController.getStoreData(String.format("%d", table_id));
        Iterator dataIter = data.iterator();
        double totalPrice = 0;
        while(dataIter.hasNext())
        {
            store_model currentObj = (store_model)dataIter.next();
            Vector row = new Vector();
            row.add(currentObj.product_id);
            row.add(currentObj.get_product_name());
            row.add(currentObj.quantity);
            row.add(currentObj.get_product_unit());
            row.add(tuocController.priceWithoutDecimal(currentObj.get_product_price()));
            row.add(tuocController.priceWithoutDecimal(currentObj.get_subTotal()));
            tblOrderModel.addRow(row);
            totalPrice += currentObj.get_subTotal();
        }
        tblOrder.setModel(tblOrderModel);
        lblTotalPrice.setText(tuocController.priceWithoutDecimal(totalPrice));
        totalMoney = totalPrice;
    }
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("tuoc?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
        productsQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Products p");
        productsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productsQuery.getResultList();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblSearchResult = new javax.swing.JTable();
        btnCancel = new javax.swing.JButton();
        txtSearchInput = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblOrder = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        btnFinish = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        lblTotalPrice = new javax.swing.JLabel();
        btnManage = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("File");
        jMenuBar2.add(jMenu3);

        jMenu4.setText("Edit");
        jMenuBar2.add(jMenu4);

        setBounds(new java.awt.Rectangle(0, 0, 1024, 768));

        tblSearchResult.setFont(new java.awt.Font("Arial Unicode MS", 0, 12)); // NOI18N

        tblSearchResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "TÊN MÓN", "ĐƠN VỊ TÍNH", "GIÁ"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblSearchResult.setColumnSelectionAllowed(true);
        tblSearchResult.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblSearchResultMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblSearchResult);
        tblSearchResult.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblSearchResult.getColumnModel().getColumn(0).setMinWidth(1);
        tblSearchResult.getColumnModel().getColumn(0).setMaxWidth(1);

        btnCancel.setText("Bàn mới");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        txtSearchInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSearchInputActionPerformed(evt);
            }
        });
        txtSearchInput.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtSearchInputKeyTyped(evt);
            }
        });

        tblOrder.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Tên món", "Số lượng", "ĐVT", "Đơn giá", "Thành tiền"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblOrder.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblOrderKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tblOrder);
        tblOrder.getColumnModel().getColumn(0).setMinWidth(1);
        tblOrder.getColumnModel().getColumn(0).setMaxWidth(1);

        jLabel1.setText("CÁC MÓN ĐÃ NHẬP");

        btnFinish.setText("Tính tiền");
        btnFinish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinishActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        jLabel2.setText("Tổng cộng:");

        lblTotalPrice.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
        lblTotalPrice.setText("0");

        btnManage.setText("Quản lý");
        btnManage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnManageActionPerformed(evt);
            }
        });

        btnRefresh.setText("Làm mới");
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(btnFinish)
                        .add(18, 18, 18)
                        .add(btnCancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 91, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(btnManage)
                            .add(btnRefresh))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(txtSearchInput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 280, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 380, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel2)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(lblTotalPrice)
                                .add(0, 0, Short.MAX_VALUE))
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(txtSearchInput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel2)
                            .add(lblTotalPrice))
                        .add(31, 31, 31))
                    .add(layout.createSequentialGroup()
                        .add(btnManage)
                        .add(18, 18, 18)
                        .add(btnRefresh)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnCancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(btnFinish))
                .add(33, 33, 33))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtSearchInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSearchInputActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSearchInputActionPerformed

    private void txtSearchInputKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSearchInputKeyTyped
                // TODO add your handling code here:
        this.set_search_table_by_search(txtSearchInput.getText());
    }//GEN-LAST:event_txtSearchInputKeyTyped

    private void tblSearchResultMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblSearchResultMousePressed
                // TODO add your handling code here:
        int selectedRow = tblSearchResult.getSelectedRow();
        String productId = tblSearchResult.getModel().getValueAt(selectedRow, 0).toString();
        try {
            String quantity = JOptionPane.showInputDialog(null,"Nhập số lượng",1).toString();
            tuocController.insertStore(String.format("%d", table_id),productId ,quantity);
            this.reloadTableOrder();        
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }//GEN-LAST:event_tblSearchResultMousePressed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        if(JOptionPane.showConfirmDialog(null, "Bạn có chắc muốn xoá hết","Cánh báo", JOptionPane.YES_NO_OPTION) == 0)
        {
            tuocController.clearStoreData(String.format("%s", table_id));
            reloadTableOrder();
        }
    }//GEN-LAST:event_btnCancelActionPerformed

    private void tblOrderKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblOrderKeyPressed
        // TODO add your handling code here:
        int selectedRow = tblOrder.getSelectedRow();
//        + KEY PRESS
        if(evt.getKeyCode() == 61)
        {
            try {
                String quantity = JOptionPane.showInputDialog(null,"Nhập số đê cộng thêm",1);
                String productId = tblOrder.getModel().getValueAt(selectedRow, 0) + "";
                tuocController.increaseStoreQuantity(table_id + "", productId, quantity);
                reloadTableOrder();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
//        - KEY PRESS
        else if(evt.getKeyCode() == 45)
        {
            try {
                String quantity = JOptionPane.showInputDialog(null,"Nhập số đê trừ",1);
                String productId = tblOrder.getModel().getValueAt(selectedRow, 0) + "";
                quantity = (0 - Integer.parseInt(quantity)) + "";
                tuocController.increaseStoreQuantity(table_id + "", productId, quantity);
                reloadTableOrder();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_tblOrderKeyPressed

    private void btnFinishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinishActionPerformed
        // TODO add your handling code here:
        tuocController.insertOrderData(tblOrder.getModel(),table_id+"",totalMoney + "");
        this.reloadTableOrder();
    }//GEN-LAST:event_btnFinishActionPerformed

    private void btnManageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManageActionPerformed
        // TODO add your handling code here:
        tuocController.show_manage_view();
    }//GEN-LAST:event_btnManageActionPerformed

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        // TODO add your handling code here:
        tuocController.reloadView();
    }//GEN-LAST:event_btnRefreshActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnFinish;
    private javax.swing.JButton btnManage;
    private javax.swing.JButton btnRefresh;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblTotalPrice;
    private java.util.List<tuoc.Products> productsList;
    private javax.persistence.Query productsQuery;
    private javax.swing.JTable tblOrder;
    private javax.swing.JTable tblSearchResult;
    private javax.swing.JTextField txtSearchInput;
    // End of variables declaration//GEN-END:variables
}
